<template>
  <div class="foreign-key-handler">
    <!-- 外键冲突提示对话框 -->
    <el-dialog
      v-model="foreignKeyDialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="foreign-key-content">
        <div class="warning-icon">
          <el-icon size="48" color="#E6A23C"><Warning /></el-icon>
        </div>
        
        <div class="message-content">
          <h3>{{ primaryMessage }}</h3>
          <p v-if="detailMessage" class="detail-message">{{ detailMessage }}</p>
          
          <!-- 关联数据列表 -->
          <div v-if="relatedData && relatedData.length > 0" class="related-data">
            <h4>以下关联数据将受到影响：</h4>
            <div class="related-list">
              <div 
                v-for="(item, index) in relatedData.slice(0, showAllRelated ? relatedData.length : 5)" 
                :key="index"
                class="related-item"
              >
                <el-tag :type="getRelatedItemType(item.type)" size="small">
                  {{ item.type }}
                </el-tag>
                <span class="item-name">{{ item.name }}</span>
                <span class="item-desc" v-if="item.description">{{ item.description }}</span>
              </div>
              
              <!-- 显示更多按钮 -->
              <div v-if="relatedData.length > 5" class="show-more">
                <el-button 
                  type="text" 
                  @click="showAllRelated = !showAllRelated"
                  size="small"
                >
                  {{ showAllRelated ? '收起' : `显示全部 ${relatedData.length} 项` }}
                  <el-icon><ArrowDown v-if="!showAllRelated" /><ArrowUp v-else /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 操作选项 -->
          <div class="action-options">
            <h4>请选择处理方式：</h4>
            <el-radio-group v-model="selectedAction" class="action-radio-group">
              <el-radio 
                v-for="action in availableActions" 
                :key="action.value"
                :label="action.value"
                :disabled="action.disabled"
                class="action-radio"
              >
                <div class="action-content">
                  <div class="action-title">{{ action.label }}</div>
                  <div class="action-desc">{{ action.description }}</div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 风险提示 -->
          <div v-if="selectedAction === 'cascade_delete'" class="risk-warning">
            <el-alert
              title="危险操作警告"
              type="error"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>此操作将永久删除所选记录及其所有关联数据，且无法恢复！</p>
                <p>请确认您已经备份了重要数据，并完全理解此操作的后果。</p>
              </template>
            </el-alert>
          </div>
          
          <!-- 确认输入 -->
          <div v-if="requireConfirmInput" class="confirm-input">
            <el-input
              v-model="confirmText"
              :placeholder="`请输入 '${confirmKeyword}' 以确认操作`"
              clearable
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button 
            :type="getConfirmButtonType()"
            :disabled="!canConfirm"
            :loading="processing"
            @click="handleConfirm"
          >
            {{ getConfirmButtonText() }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Warning, ArrowDown, ArrowUp } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  entityType: {
    type: String,
    required: true
  },
  entityName: {
    type: String,
    required: true
  },
  errorMessage: {
    type: String,
    default: ''
  },
  relatedData: {
    type: Array,
    default: () => []
  },
  onResolve: {
    type: Function,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'resolved'])

// 响应式数据
const foreignKeyDialogVisible = ref(false)
const selectedAction = ref('')
const showAllRelated = ref(false)
const confirmText = ref('')
const processing = ref(false)

// 根据实体类型配置不同的处理选项
const actionConfigs = {
  user: {
    cascade_delete: {
      label: '级联删除',
      description: '删除用户及其所有关联数据（余额记录、充值记录等）',
      dangerous: true,
      confirmKeyword: 'DELETE'
    },
    soft_delete: {
      label: '软删除',
      description: '标记用户为已删除状态，保留所有关联数据',
      dangerous: false
    },
    transfer_data: {
      label: '转移数据',
      description: '将关联数据转移到其他用户，然后删除此用户',
      dangerous: false,
      disabled: true // 暂不支持
    }
  },
  recharge: {
    soft_delete: {
      label: '软删除',
      description: '标记充值记录为已删除状态，不影响用户余额',
      dangerous: false
    },
    cascade_delete: {
      label: '强制删除',
      description: '删除充值记录并调整用户余额',
      dangerous: true,
      confirmKeyword: 'DELETE'
    }
  },
  balance: {
    reset_balance: {
      label: '重置余额',
      description: '将余额重置为0，然后删除记录',
      dangerous: true,
      confirmKeyword: 'RESET'
    },
    soft_delete: {
      label: '软删除',
      description: '标记余额记录为已删除状态',
      dangerous: false
    }
  }
}

// 计算属性
const dialogTitle = computed(() => {
  return `删除${getEntityTypeName()}时遇到关联数据`
})

const primaryMessage = computed(() => {
  return `无法删除"${props.entityName}"，因为存在关联数据`
})

const detailMessage = computed(() => {
  if (props.errorMessage) {
    return `错误详情：${props.errorMessage}`
  }
  return '为了保证数据完整性，请先处理相关联的数据。'
})

const availableActions = computed(() => {
  const config = actionConfigs[props.entityType] || {}
  return Object.entries(config).map(([key, action]) => ({
    value: key,
    label: action.label,
    description: action.description,
    disabled: action.disabled || false,
    dangerous: action.dangerous || false,
    confirmKeyword: action.confirmKeyword || ''
  }))
})

const requireConfirmInput = computed(() => {
  const action = availableActions.value.find(a => a.value === selectedAction.value)
  return action && action.dangerous && action.confirmKeyword
})

const confirmKeyword = computed(() => {
  const action = availableActions.value.find(a => a.value === selectedAction.value)
  return action ? action.confirmKeyword : ''
})

const canConfirm = computed(() => {
  if (!selectedAction.value) return false
  if (requireConfirmInput.value) {
    return confirmText.value === confirmKeyword.value
  }
  return true
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  foreignKeyDialogVisible.value = newVal
  if (newVal) {
    resetDialog()
  }
})

watch(foreignKeyDialogVisible, (newVal) => {
  if (!newVal) {
    emit('update:visible', false)
  }
})

// 方法
const getEntityTypeName = () => {
  const typeNames = {
    user: '用户',
    recharge: '充值记录',
    balance: '余额记录',
    role: '角色',
    menu: '菜单'
  }
  return typeNames[props.entityType] || '记录'
}

const getRelatedItemType = (type) => {
  const typeMap = {
    balance: 'warning',
    recharge: 'success',
    consumption: 'info',
    role: 'primary',
    menu: 'danger'
  }
  return typeMap[type] || 'info'
}

const getConfirmButtonType = () => {
  if (selectedAction.value === 'cascade_delete' || selectedAction.value === 'reset_balance') {
    return 'danger'
  }
  return 'primary'
}

const getConfirmButtonText = () => {
  const action = availableActions.value.find(a => a.value === selectedAction.value)
  if (!action) return '确认'
  
  if (action.dangerous) {
    return processing.value ? '处理中...' : '确认执行'
  }
  return processing.value ? '处理中...' : '确认'
}

const resetDialog = () => {
  selectedAction.value = ''
  showAllRelated.value = false
  confirmText.value = ''
  processing.value = false
  
  // 默认选择第一个非危险选项
  const safeAction = availableActions.value.find(a => !a.dangerous && !a.disabled)
  if (safeAction) {
    selectedAction.value = safeAction.value
  }
}

const handleCancel = () => {
  foreignKeyDialogVisible.value = false
}

const handleConfirm = async () => {
  if (!canConfirm.value) return
  
  try {
    processing.value = true
    
    // 调用解决方案处理函数
    await props.onResolve({
      action: selectedAction.value,
      entityType: props.entityType,
      entityName: props.entityName,
      confirmText: confirmText.value
    })
    
    ElMessage.success('操作完成')
    foreignKeyDialogVisible.value = false
    emit('resolved', selectedAction.value)
    
  } catch (error) {
    console.error('处理外键约束失败:', error)
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  } finally {
    processing.value = false
  }
}

// 暴露给父组件的方法
defineExpose({
  show: () => {
    foreignKeyDialogVisible.value = true
  },
  hide: () => {
    foreignKeyDialogVisible.value = false
  }
})
</script>

<style scoped>
.foreign-key-content {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.warning-icon {
  flex-shrink: 0;
  margin-top: 10px;
}

.message-content {
  flex: 1;
}

.message-content h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.detail-message {
  color: #666;
  margin: 0 0 20px 0;
  line-height: 1.5;
}

.related-data {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.related-data h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 14px;
}

.related-list {
  max-height: 200px;
  overflow-y: auto;
}

.related-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.related-item:last-child {
  border-bottom: none;
}

.item-name {
  font-weight: 500;
  color: #333;
}

.item-desc {
  color: #666;
  font-size: 12px;
}

.show-more {
  text-align: center;
  padding: 10px 0;
}

.action-options {
  margin: 20px 0;
}

.action-options h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 14px;
}

.action-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-radio {
  margin: 0;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  transition: all 0.3s;
}

.action-radio:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.action-radio.is-checked {
  border-color: #409eff;
  background: #f0f9ff;
}

.action-content {
  margin-left: 8px;
}

.action-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.action-desc {
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

.risk-warning {
  margin: 20px 0;
}

.confirm-input {
  margin: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .foreign-key-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .warning-icon {
    text-align: center;
    margin-top: 0;
  }
}
</style> 